<template>
  <div class="working-time-editor">
    <el-form label-width="72px">
      <!-- 基本信息 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="ID">
            <el-input v-model="localData.id" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="名称">
            <el-input v-model="localData.name" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="科室">
            <!-- <el-input-number v-model="localData.orgId" :min="1" /> -->
            <el-select v-model="localData.orgId" placeholder="请选择科室">
              <el-option
                v-for="item in optionProfile.organizations"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="描述">
            <el-input v-model="localData.description" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 工作时间段 -->
    <div class="working-times-section">
      <div class="section-header">
        <div>工作时间段</div>
        <el-button type="primary" link @click="addWorkingTime"
          >添加时间段</el-button
        >
      </div>
      <div
        class="time-item-card"
        v-for="(time, index) in localData.workingTimes"
      >
        <div class="time-item-card-header">
          <span>时间段 {{ index + 1 }}</span>
          <el-button type="danger" link @click="removeWorkingTime(index)">
            删除
          </el-button>
        </div>
        <el-form label-width="96px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="日期偏移">
                <el-slider
                  v-model="time.dayOffset"
                  :min="0"
                  :max="3"
                  :step="1"
                  show-stops
                  style="margin: 0 12px; max-width: 120px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级">
                <el-rate v-model="time.priority" :max="5" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-time-picker
                  v-model="time.from"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择开始时间"
                  :clearable="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-time-picker
                  v-model="time.to"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择结束时间"
                  :clearable="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="优先座位">
                <!-- <el-checkbox
                  v-model="time.hasSeatTypePref"
                  @change="onSeatTypePrefChange(time)"
                ></el-checkbox> -->
                <!-- v-if="time.hasSeatTypePref" -->
                <el-select
                  v-model="time.seatTypePref"
                  multiple
                  placeholder="选择座位优先级"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in optionProfile.seatTypes"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 预览 -->
    <div class="working-times-section">
      <div class="section-header">
        <div>原始数据</div>
      </div>
      <div class="time-item-card">
        <pre>{{ formattedData }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup>
import optionProfile from "@/profiles/options.json";

// 定义props
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emits
const emit = defineEmits(["update:modelValue"]);

// 创建本地数据副本，避免直接修改props
const localData = ref({
  id: "",
  name: "",
  description: "",
  orgId: 1,
  workingTimes: [],
});

// 初始化默认的工作时间段
const createDefaultWorkingTime = () => ({
  dayOffset: 0,
  from: "09:00",
  to: "17:00",
  priority: 3,
  // hasSeatTypePref: false,
  seatTypePref: [],
});

// 添加工作时间段
const addWorkingTime = () => {
  localData.value.workingTimes.push(createDefaultWorkingTime());
  emitUpdate();
};

// 删除工作时间段
const removeWorkingTime = (index) => {
  if (localData.value.workingTimes.length <= 1) {
    ElMessage.warning("至少需要保留一个工作时间段");
    return;
  }
  localData.value.workingTimes.splice(index, 1);
  emitUpdate();
};

// 座位类型偏好复选框变化处理;
const onSeatTypePrefChange = (time) => {
  if (!time.hasSeatTypePref) {
    time.seatTypePref = [];
  }
  // emitUpdate();
  // 不需要立即触发更新，等待其他可能的变更
  nextTick(() => {
    emitUpdate();
  });
};

// 格式化输出数据（处理seatTypePref字段）
const formattedData = computed(() => {
  return JSON.stringify(formatDataForEmit(localData.value), null, 2);
});

// 格式化数据用于emit
const formatDataForEmit = (data) => {
  const formatted = JSON.parse(JSON.stringify(data));

  formatted.workingTimes = formatted.workingTimes.map((time) => {
    const result = {
      dayOffset: time.dayOffset,
      from: time.from,
      to: time.to,
      priority: time.priority,
      seatTypePref: time.seatTypePref || [],
    };

    // if (
    //   time.hasSeatTypePref &&
    //   time.seatTypePref &&
    //   time.seatTypePref.length > 0
    // ) {
    //   result.seatTypePref = [...time.seatTypePref];
    // }

    // if (time.seatTypePref) {
    //   result.seatTypePref = [...time.seatTypePref];
    // }

    return result;
  });

  return formatted;
};

// 触发更新事件
const emitUpdate = () => {
  emit("update:modelValue", formatDataForEmit(localData.value));
};

// 初始化数据 - 只在props变化时更新，避免循环
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && Object.keys(newValue).length > 0) {
      const data = JSON.parse(JSON.stringify(newValue));

      if (data.workingTimes) {
        // 处理workingTimes数据，添加hasSeatTypePref字段
        data.workingTimes = data.workingTimes.map((time) => ({
          ...time,
          hasSeatTypePref: true,
          // hasSeatTypePref: !!(
          //   time.seatTypePref && time.seatTypePref.length > 0
          // ),
          seatTypePref: time.seatTypePref || [],
        }));
      } else {
        data.workingTimes = [];
      }

      localData.value = data;
    }
  },
  { immediate: true }
);

// 监听本地数据变化并触发更新（使用debounce避免频繁触发）
let updateTimeout = null;
watch(
  localData,
  () => {
    if (updateTimeout) {
      clearTimeout(updateTimeout);
    }
    updateTimeout = setTimeout(() => {
      emitUpdate();
    }, 300);
  },
  { deep: true }
);

// 如果没有工作时间段，添加一个默认的
if (localData.value.workingTimes.length === 0) {
  addWorkingTime();
}
</script>

<style scoped>
.working-time-editor {
  padding: 16px;
}

.working-times-section {
  margin: 16px 0;
  font-size: 14px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.time-item-card {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #8888;
  margin-bottom: 16px;
}

.time-item-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #8888;
}

.help-text {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.preview-section {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #8888;
}
</style>
